﻿using MvcBoost;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace System.Web.Mvc.Html
{
    public static class HtmlHelperTagExtensions
    {
        public static MvcHtmlString Tag<TModel>(this HtmlHelper<TModel> helper, string tagName, string className, object htmlAttributes, params Func<HtmlHelper<TModel>, object>[] innerElements)
        {
            StringBuilder sb = new StringBuilder();

            TagBuilder tag = new TagBuilder(tagName);

            tag.MergeAttributes(MvcTools.Extend(htmlAttributes));

            if (!String.IsNullOrWhiteSpace(className)) tag.AddCssClass(className);

            sb.Append(tag.ToString(TagRenderMode.StartTag));

            if (innerElements != null)
            {
                foreach (var f in innerElements)
                {
                    sb.Append(f(helper));
                }
            }

            sb.Append(tag.ToString(TagRenderMode.EndTag));
            return MvcHtmlString.Create(sb.ToString());
        }

        public static MvcHtmlString Tag<TModel>(this HtmlHelper<TModel> helper, string tagName, string className, object htmlAttributes, object innerText)
        {
            return Tag<TModel>(helper,tagName, className, htmlAttributes, _h=>_h.Encode(innerText));
        }

        public static IDisposable BeginTag<TModel>(this HtmlHelper<TModel> helper, string tagName, string className, object htmlAttributes)
        {
            StringBuilder sb = new StringBuilder();

            TagBuilder tag = new TagBuilder(tagName);

            tag.MergeAttributes(MvcTools.Extend(htmlAttributes));

            if (!String.IsNullOrWhiteSpace(className)) tag.AddCssClass(className);

            HtmlViewWriterExtensions.Write(helper, tag.ToString(TagRenderMode.StartTag));

            return helper.BeginDisposable(h=>h.Write(tag.ToString(TagRenderMode.EndTag)));            
        }


    }
}
